#include "server.h"


char *get_ip(void)
{
  int s;
  struct ifconf ifconf;
  struct ifreq ifr[50];
  int ifs;
  int i;
  char *ip_addr = NULL;

  char ip[INET_ADDRSTRLEN];
  struct sockaddr_in *s_in;

  s = socket(AF_INET, SOCK_STREAM, 0);

  if (s < 0)
  {
    perror("socket");
    return 0;
  }

  ifconf.ifc_buf = (char *) ifr;
  ifconf.ifc_len = sizeof ifr;

  if (ioctl(s, SIOCGIFCONF, &ifconf) == -1)
  {
    perror("ioctl");
    return 0;
  }

  ifs = ifconf.ifc_len / sizeof(ifr[0]);

  if ((ip_addr = malloc(16 * sizeof(char))) == NULL)
    return NULL;

  for (i = 0; i < ifs; i++)
  {

    s_in = (struct sockaddr_in *) &ifr[i].ifr_addr;

    if (!inet_ntop(AF_INET, &s_in->sin_addr, ip, sizeof(ip)))
    {
      perror("inet_ntop");
      return 0;
    }

    if (strcmp(ip, "127.0.0.1") != 0)
      strcpy(ip_addr, ip);
    //      printf("%s\n", ip);

  }

  close(s);

  return ip_addr;
}

char *get_ip2()
{

  FILE *fd;
  char *buf;

  buf = malloc (16 * sizeof(char));

  system("ip -f inet -o addr | grep eth | tr -s ' ' | cut -d ' ' -f 4-8| cut -d '/' -f 1 > ip.txt");

  fd = fopen("ip.txt","r");

  if (fd != NULL)
    {
      fscanf (fd, "%s", buf);
    }

  fclose(fd);
  system("rm ip.txt");
  return (buf);
}

char *get_groupip(char *src)
{
  char *tmp;
  char *ip1 = "239.42.";
  char *ip2 = ".2";
  char *groupip;

  tmp = malloc (3 * sizeof(char));
  tmp = strtok(src, ".");
  tmp = strtok(NULL, ".");
  tmp = strtok(NULL, ".");

  groupip = malloc(16 * sizeof(char));

  groupip = strcat(groupip, ip1);
  groupip = strcat(groupip, tmp);
  groupip = strcat(groupip, ip2);

  return (groupip);
}
